﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WordpressDemo.Models
{
    /// <summary>Filter rejecting anonymous users.</summary>
    public class NotAllowAnonymousAttribute : ActionFilterAttribute
    {
        /// <summary>Called when the action must execute.</summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var actionDesc = filterContext.ActionDescriptor;
            var isAllowedOnMethod =
                actionDesc.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any();
            var isAllowedOnController =
                actionDesc.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any();

            if (!isAllowedOnController
                && !isAllowedOnController
                && !filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
}